package com.yusheng.tr.common.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yusheng.tr.common.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @ClassName jiang_jun_qin
 * @date 2023/3/24 13:13
 * @Version 1.0
 */
@Component
@Slf4j
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间，取当前时间，也可以自定义
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        // 创建人id，这个看自身业务如何获取，我这里是获取的保存在上下文（ThreadLocal）中的用户id
        this.strictInsertFill(metaObject, "createBy", String.class, SecurityUtils.getLoginUser() == null ? "-1L" : SecurityUtils.getLoginUser().getUser()==null?"-1":SecurityUtils.getLoginUser().getUser().getUserName() + "");

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间，取当前时间，也可以自定义
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        // 更新人id，这个看自身业务如何获取，我这里是获取的保存在上下文（ThreadLocal）中的用户id
        this.strictUpdateFill(metaObject, "updateBy", String.class, SecurityUtils.getLoginUser() == null ? "-1L" : SecurityUtils.getLoginUser().getUser()==null?"-1":SecurityUtils.getLoginUser().getUser().getUserName());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        if (metaObject.getValue(fieldName) == null) //不判断空值情况即可
        {
            Object obj = fieldVal.get();
            if (Objects.nonNull(obj)) {
                metaObject.setValue(fieldName, obj);
            }
        }
        return this;
    }
}
